import React, { useEffect, useState } from 'react';
import { connect } from 'dva';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Divider, message, Popconfirm, Space, Table, Card } from 'antd';
import { PlusOutlined } from "@ant-design/icons";
import { ModalForm, ProFormText } from "@ant-design/pro-form";
import Authorized, { includesKey } from '@/components/Authorized';



const formLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 16 }
}

const RoleList: React.FC = (props: any) => {
  const { dispatch, params } = props;


  // 表格数据
  const [list, setList] = useState([])
  const [menuTreeList, setMenuTreeList] = useState([])
  const [record, setRecord] = useState(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [selectedRowKeysWithParentId, setSelectedRowKeysWithParentId] = useState<string[]>([]);
  // 新增弹窗visible
  const [modalVisible, setModalVisible] = useState(false);
  const [menuModalVisible, setMenuModalVisible] = useState(false);

  const getList = () => {
    dispatch({
      type: 'role/findList',
      payload: {},
      callback: (e) => {
        if (e.code === 1) {
          setList(e.data)
        } else {
          message.error(e.msg || '查询失败')
        }
      }
    })
  }

  const getKeys = (keys: string[], keysWithParentId: string[], menuList: any[]) => {
    menuList.forEach(e => {
      if (e.roleId) {
        keysWithParentId.push(e.id);
        if (!e.children) {
          keys.push(e.id);
        }
      }
      if (e.children && e.children.length > 0) {
        getKeys(keys, keysWithParentId, e.children);
      }
    })
    return keys;
  }

  // 获取树数据
  const findRoleMenuTree = (roleId: string) => {
    dispatch({
      type: 'sysMenu/findRoleMenuTree',
      payload: roleId,
      callback: (e) => {
        if (e.code === 1) {
          setMenuTreeList(e.data);
          const keys: string[] = [];
          const keysWithParentId: string[] = [];
          getKeys(keys, keysWithParentId, e.data);
          setSelectedRowKeys(keys);
          setSelectedRowKeysWithParentId(keysWithParentId);
        } else {
          message.error(e.msg || '查询失败')
        }
      }
    });
  };

  // 获取树数据
  const updateRoleMenu = () => {
    dispatch({
      type: 'sysMenu/updateRoleMenu',
      payload: { roleId: record.id, menuIds: selectedRowKeysWithParentId },
      callback: (e) => {
        if (e.code === 1) {
          message.success('操作成功');
          setMenuModalVisible(false);
        } else {
          message.error(e.msg || '查询失败')
        }
      }
    });
  };


  // 监听数据变化
  useEffect(() => {
    getList()
  }, []);

  const handleDelete = (id: string) => {
    dispatch({
      type: 'role/delete',
      payload: {id},
      callback: (e) => {
        if (e.code === 1) {
          message.success('删除成功');
          getList();
        } else {
          message.error(e.msg || '删除失败');
        }
      }
    });
  }


  const menuColumns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    }]


  // 打开或关闭弹窗
  const handleModalVisible = (_record: any) => {
    setRecord(_record || null);
    setModalVisible(!modalVisible);
  }

  // 打开或关闭弹窗
  const handleMenuModalVisible = (_record: any) => {
    if (_record) {
      setRecord(_record);
      findRoleMenuTree(_record.id);
    }
    setMenuModalVisible(!menuModalVisible);

  }

  const onSelectChange = (keys: string[], rows: any[]) => {
    const set = new Set();
    rows.forEach(e => {
      set.add(e.id);
      if (e.parentId !== '0') {
        set.add(e.parentId);
      }
    })
    setSelectedRowKeys(keys)
    setSelectedRowKeysWithParentId([...set])
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const columns = [
    {
      title: '角色',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime'
    },

  ];

  includesKey(columns,["role:update","role:delete"],
    {
      title: '操作',
      key: 'action',
      render: (text: string, r: any) => (
        <Space size={0}>


          <Authorized authority="role:update">
            <Button type="link" onClick={() => {
              handleModalVisible(r)
            }}>编辑</Button>

          </Authorized>
          <Divider type="vertical" />
          <Authorized authority="role:update">
            <Button type="link" onClick={() => {
              handleMenuModalVisible(r)
            }}>授权</Button>
          </Authorized>
          <Divider type="vertical" />
          <Authorized authority="role:delete">
            {['admin', 'merchantAdmin'].includes(r.roleCode) ? '' :
              <>

                <Popconfirm title="确认删除吗" onConfirm={() => {
                  handleDelete(r.id)
                }}>
                  <Button type="link">删除</Button>
                </Popconfirm>
              </>
            }
          </Authorized>
        </Space>
      ),
    }
   )

  // 表单提交
  const onFinish = (values: any) => {
    if (record) {
      values.id = record.id
    }
    if (record) {
      dispatch({
        type: 'role/updateObject',
        payload: values,
        callback: (e) => {
          if (e.code === 1) {
            message.success('修改成功');
            getList();
            handleModalVisible(null);
          } else {
            message.error(e.msg || '修改失败');
          }
        }
      });
    } else {
      dispatch({
        type: 'role/saveObject',
        payload: values,
        callback: (e) => {
          if (e.code === 1) {
            message.success('新增成功');
            getList();
            handleModalVisible(null);
          } else {
            message.error(e.msg || '新增失败');
          }
        }
      });
    }
  }

  return (
    <div>
        <Space align="center" style={{ marginBottom: 16 }}>
          <Authorized authority="role:save">
            <Button type="primary" onClick={() => {
              handleModalVisible(null)
            }}>
              <PlusOutlined />
              新建
            </Button>
          </Authorized>
          <ModalForm<{
            roleName: string;
            roleCode: string;
          }>
            {...formLayout}
            layout="horizontal"
            width="600px"
            title={record ? "编辑角色" : "新建角色"}
            visible={modalVisible}
            initialValues={record}
            modalProps={{
              onCancel: () => {
                handleModalVisible(null)
              },
              destroyOnClose: true,
              maskClosable: false
            }}
            onFinish={onFinish}
          >
            <ProFormText width="xl" name="roleName" label="角色名称" rules={[{ required: true, message: '请输入角色名称' }]} />
            {/* <ProFormText width="xl" name="roleCode" label="角色code" rules={[{ required: true, message: '请输入角色code' }]} /> */}
          </ModalForm>
          <ModalForm<{}>
            {...formLayout}
            layout="horizontal"
            width="600px"
            title="授权"
            visible={menuModalVisible}
            // initialValues={record}
            modalProps={{
              onCancel: () => {
                handleMenuModalVisible(null)
              },
              destroyOnClose: true
            }}
            onFinish={updateRoleMenu}
          >
            <Table
              columns={menuColumns}
              dataSource={menuTreeList}
              rowSelection={{ ...rowSelection, checkStrictly: false }}
              rowKey="id"
            />
          </ModalForm>
        </Space>
        <Table
          columns={columns}
          dataSource={list}
        />
      </div>
  );
};
export default connect(({ roleList }) => ({ roleList }))(RoleList);
